package com.wanlian.net.core;

import com.wanlian.File.DateStorageItem;
import com.wanlian.File.FileUtils;
import com.wanlian.File.NetFileInfo;
import com.wanlian.File.StorageItem;
import com.wanlian.json.JsonStringUtil;
import com.wanlian.netty.model.NetFileInfoRecord;
import com.wanlian.netty.model.ResultInfo;
import com.wanlian.netty.msg.Device.*;
import com.wanlian.netty.msg.Device.model.*;
import com.wanlian.netty.msg.MsgType;
import com.wanlian.netty.msg.PeerMsg;
import com.wanlian.netty.msg.PeerMsgQueue;
import com.wanlian.netty.msg.ResultMsg;
import com.wanlian.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


public class DeviceClientWorker {
    private static Logger logger = LoggerFactory.getLogger(DeviceClientWorker.class);
    private static ClientSocket peer;
    private static Map<String, NetFileInfoRecord> netFileDir = new HashMap<>();
    private static Map<String, NetFileInfoRecord> readFileDir = new HashMap();
    private static Map<String, NetFileInfoRecord> needContinueDownFileDir = new HashMap<>();
    private static Map<String, NetFileInfoRecord> needContinueUpFileDir = new HashMap<>();


    public void work() {
        start();
        loadFile();
        sendThread();
        keepConnect();
        sendContinueThread();
    }

    /**
     * 处理消息
     */
    private void start() {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            fixedThreadPool.execute(new Runnable() {
                public void run() {
                    while (true) {
                        try {
                            TimeUnit.MILLISECONDS.sleep(10);
                            processMsg();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    }

    private void loadFile() {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            fixedThreadPool.execute(new Runnable() {
                public void run() {
                    while (true) {
                        try {
                            TimeUnit.MILLISECONDS.sleep(20);
                            writeFile();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    }

    private void sendContinueThread() {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);
        for (int i = 0; i < 5; i++) {
            fixedThreadPool.execute(new Runnable() {
                public void run() {
                    while (true) {
                        try {
                            readContinueDownFile();
                            TimeUnit.MILLISECONDS.sleep(20);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    }


    private void sendThread() {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);
        fixedThreadPool.execute(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        readFile();
                        TimeUnit.MILLISECONDS.sleep(20);
                        sendFile();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


    private void keepConnect() {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);
        fixedThreadPool.execute(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        TimeUnit.MILLISECONDS.sleep(100);
                        //检查peer的状态
                        peer.keepConnect();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private synchronized void processMsg() {
        PeerMsg peerMsg = PeerMsgQueue.get();
        if (peerMsg != null) {
            String msgType = peerMsg.getBaseMsg().getType();
            String clientId = peerMsg.getBaseMsg().getClientId();
            switch (msgType) {
                case MsgType.PING:
                    String response = "PING REVICED";
                    //logger.info(response);
                    break;
                case MsgType.PING_REPLY:
                    //logger.info(peerMsg.getBaseMsg().toString());
                    break;
                case MsgType.REGISTER_SUCCESS:
                    //logger.info(MsgType.REGISTER_SUCCESS);
                    break;
                case MsgType.DEVICE_STATUS_UPANDDOWNSIZE_REQ:
                    //获取上行，下行速率
                    StatusUpAndDownSizeReply statusUpAndDownSizeReply = new StatusUpAndDownSizeReply();
                    UpAndDownSize upAndDownSize = new UpAndDownSize();
                    upAndDownSize.setDown(1);
                    upAndDownSize.setUp(99);
                    statusUpAndDownSizeReply.setUpAndDownSize(upAndDownSize);
                    statusUpAndDownSizeReply.setTagClientId(clientId);
                    peer.sendSNData(statusUpAndDownSizeReply);
                    break;
                case MsgType.DEVICE_PPPOE_SET:
                    //拨号连接
                    PPPoE ppPoE = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), PPPoE.class);
                    System.out.println(peerMsg.getBaseMsg().getContent());
                   /* PPPoEReply ppPoEReply = new PPPoEReply();
                    ppPoEReply.setClientId(this.getPeer().getPubkey());
                    ppPoEReply.setTagClientId(clientId);*/
                    ResultMsg resultMsg = new ResultMsg(MsgType.COMMON_SUCCESS);
                    resultMsg.setReplyType(MsgType.DEVICE_PPPOE_SET);
                    resultMsg.setClientId(peer.getPubkey());
                    resultMsg.setTagClientId(peerMsg.getBaseMsg().getClientId());
                    peer.sendSNData(resultMsg);
                    logger.info(resultMsg.toString());
                    break;
                case MsgType.DEVICE_TWOWIFI_SET:
                    //2.4G网设置
                    TwoAndFiveWifiInfo twoAndFiveWifiInfo = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), TwoAndFiveWifiInfo.class);
                    System.out.println(peerMsg.getBaseMsg().getContent());
                    /* TwoWifiRsp twoWifiRsp = new TwoWifiRsp();*/
                    ResultMsg resultMsg1 = new ResultMsg(MsgType.COMMON_SUCCESS);
                    resultMsg1.setReplyType(MsgType.DEVICE_TWOWIFI_SET);
                    resultMsg1.setClientId(peer.getPubkey());
                    resultMsg1.setTagClientId(peerMsg.getBaseMsg().getClientId());
                    logger.info(resultMsg1.toString());
                    peer.sendSNData(resultMsg1);
                    break;
                case MsgType.DEVICE_FIVEWIFI_SET:
                    //5G网设置
                    TwoAndFiveWifiInfo twoAndFiveWifiInfof = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), TwoAndFiveWifiInfo.class);
                    System.out.println(peerMsg.getBaseMsg().getContent());
                    /*FiveWifiRsp fiveWifiRsp = new FiveWifiRsp();*/
                    ResultMsg resultMsg2 = new ResultMsg(MsgType.COMMON_SUCCESS);
                    resultMsg2.setReplyType(MsgType.DEVICE_FIVEWIFI_SET);
                    resultMsg2.setClientId(peer.getPubkey());
                    resultMsg2.setTagClientId(peerMsg.getBaseMsg().getClientId());
                    logger.info(resultMsg2.toString());
                    peer.sendSNData(resultMsg2);
                    break;
                case MsgType.DEVICE_CUSTOMERWIFI_SET:
                    //访客网络设置
                    TwoAndFiveWifiInfo twoAndFiveWifiInfoc = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), TwoAndFiveWifiInfo.class);
                    System.out.println(peerMsg.getBaseMsg().getContent());
                    /* CustomerWifiRsp customerWifiRsp = new CustomerWifiRsp();*/
                    ResultMsg resultMsg3 = new ResultMsg(MsgType.COMMON_SUCCESS);
                    resultMsg3.setReplyType(MsgType.DEVICE_CUSTOMERWIFI_SET);
                    resultMsg3.setClientId(peer.getPubkey());
                    resultMsg3.setTagClientId(peerMsg.getBaseMsg().getClientId());
                    logger.info(resultMsg3.toString());
                    peer.sendSNData(resultMsg3);
                    break;
                case MsgType.DEVICE_NET_STATIC_SET:
                    //静态IP设置
                    IpInfo static_ipInfo = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), IpInfo.class);
                    System.out.println(peerMsg.getBaseMsg().getContent());
                    /* StaticIpInfoReply staticIpInfoReply = new StaticIpInfoReply();*/
                    ResultMsg resultMsg4 = new ResultMsg(MsgType.COMMON_SUCCESS);
                    resultMsg4.setReplyType(MsgType.DEVICE_NET_STATIC_SET);
                    resultMsg4.setClientId(peer.getPubkey());
                    resultMsg4.setTagClientId(peerMsg.getBaseMsg().getClientId());
                    logger.info(resultMsg4.toString());
                    peer.sendSNData(resultMsg4);
                    break;
                case MsgType.DEVICE_NET_DYMIC_SET:
                    //动态IP设置
                    DymacIpInfo dymacIpInfo = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), DymacIpInfo.class);
                    System.out.println(peerMsg.getBaseMsg().getContent());
                   /* DymaicIpInfoRsp dymaicIpInfoRsp = new DymaicIpInfoRsp();
                    peer.sendSNData(dymaicIpInfoRsp);*/
                    ResultMsg resultMsg5 = new ResultMsg(MsgType.COMMON_SUCCESS);
                    resultMsg5.setReplyType(MsgType.DEVICE_NET_DYMIC_SET);
                    resultMsg5.setClientId(peer.getPubkey());
                    resultMsg5.setTagClientId(peerMsg.getBaseMsg().getClientId());
                    logger.info(resultMsg5.toString());
                    peer.sendSNData(resultMsg5);
                    break;
                case MsgType.DEVICE_DISK_SET:
                    Disk disk = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), Disk.class);
                    System.out.println(peerMsg.getBaseMsg().getContent());
                    /*DiskGetReply diskGetReply = new DiskGetReply();
                    peer.sendSNData(diskGetReply);*/
                    ResultMsg resultMsg6 = new ResultMsg(MsgType.COMMON_SUCCESS);
                    resultMsg6.setReplyType(MsgType.DEVICE_DISK_SET);
                    resultMsg6.setClientId(peer.getPubkey());
                    resultMsg6.setTagClientId(peerMsg.getBaseMsg().getClientId());
                    logger.info(resultMsg6.toString());
                    peer.sendSNData(resultMsg6);
                    break;
                case MsgType.DEVICE_LIMITSPEED_SET:
                    //设备限速
                    NetDevice speedDevice = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), NetDevice.class);
                    System.out.println(peerMsg.getBaseMsg().getContent());
                   /* DeviceLimitGetRsMsg deviceLimitRsp = new DeviceLimitGetRsMsg();
                    peer.sendSNData(deviceLimitRsp);*/
                    ResultMsg resultMsg7 = new ResultMsg(MsgType.COMMON_SUCCESS);
                    resultMsg7.setReplyType(MsgType.DEVICE_LIMITSPEED_SET);
                    resultMsg7.setClientId(peer.getPubkey());
                    resultMsg7.setTagClientId(peerMsg.getBaseMsg().getClientId());
                    logger.info(resultMsg7.toString());
                    peer.sendSNData(resultMsg7);
                    break;

                case MsgType.DEVICE_LIMITSPEED_REQ:
                    //设备限速
                    NetDevice NDevice = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), NetDevice.class);
                    System.out.println(peerMsg.getBaseMsg().getContent());
                    DeviceLimitGetRsMsg deviceLimitGetRsMsg = new DeviceLimitGetRsMsg();
                    UpAndDownSize upAndDownSize1 = new UpAndDownSize(10000, 20000);
                    deviceLimitGetRsMsg.setUpAndDownSize(upAndDownSize1);
                    deviceLimitGetRsMsg.setReplyType(MsgType.DEVICE_LIMITSPEED_REQ);
                    deviceLimitGetRsMsg.setClientId(peer.getPubkey());
                    deviceLimitGetRsMsg.setTagClientId(peerMsg.getBaseMsg().getClientId());
                    peer.sendSNData(deviceLimitGetRsMsg);
                    break;
                case MsgType.DEVICE_STATUS_CURRENT_REQ:
                    //获取当前网络信息
                    CurrentIpInfoReply currentIpInfoReply = new CurrentIpInfoReply();
                    CurrentIpInfo currentIpInfo = new CurrentIpInfo();
                    IpInfo ipInfoc = new IpInfo();
                    ipInfoc.setChild("192.168.1.10");
                    ipInfoc.setDns1("255.255.255.0");
                    ipInfoc.setDns2("255.255.255.0");
                    ipInfoc.setIp("192.168.1.172");
                    ipInfoc.setWlan("192.168.1.1");
                    currentIpInfo.setIpInfo(ipInfoc);
                    currentIpInfoReply.setIpInfo(currentIpInfo);
                    currentIpInfoReply.setTagClientId(clientId);
                    peer.sendSNData(currentIpInfoReply);
                    break;
                case MsgType.DEVICE_LOADING_REQ:
                    //获取设置页面加载信息
                    LoadingGetReply loadingGetReply = new LoadingGetReply();
                    LoadingInfo loadingInfo = new LoadingInfo();
                    loadingInfo.setBlackcount(5);
                    loadingInfo.setProto("static");
                    loadingInfo.setVersion("Version_1.1");
                    loadingGetReply.setLoadingInfo(loadingInfo);
                    loadingGetReply.setTagClientId(clientId);
                    peer.sendSNData(loadingGetReply);
                    break;
                case MsgType.DEVICE_NET_DEVICE_REQ:
                    //获取在线设备
                    List<NetDevice> list = new ArrayList<NetDevice>();
                    for (int i = 0; i < 10; i++) {
                        NetDevice netDevice = new NetDevice();
                        netDevice.setDeviceId("864267636~~~" + i);
                        netDevice.setName("蜡笔小新" + i);
                        netDevice.setIp("192.168.0." + i);
                        netDevice.setLoginTime(200);
                        netDevice.setNetworkName("2.4G");
                        netDevice.setMacAddress("08:00:20:0A:8C:3" + i);
                        UpAndDownSize upAndDownSized = new UpAndDownSize();
                        upAndDownSized.setUp(60 + i);
                        upAndDownSized.setDown(75 + i);
                        netDevice.setUpAndDownSize(upAndDownSized);
                        netDevice.setAccess(false);
                        list.add(netDevice);
                    }
                    NetDeviceReply netDeviceReply = new NetDeviceReply();
                    netDeviceReply.setDevices(list);
                    netDeviceReply.setTagClientId(clientId);
                    peer.sendSNData(netDeviceReply);
                    break;
                case MsgType.DEVICE_BLACKLIST_REQ:
                    //获取黑名单设备
                    List<NetDevice> lists = new ArrayList<NetDevice>();
                    for (int i = 0; i < 1; i++) {
                        NetDevice blackDevice = new NetDevice();
                        blackDevice.setDeviceId("864267636~~~" + i);
                        blackDevice.setName("蜡笔小新" + i);
                        blackDevice.setMacAddress("08:00:20:0A:8C:31" + i);
                        UpAndDownSize upAndDownSize2 = new UpAndDownSize();
                        upAndDownSize2.setUp(60 + i);
                        upAndDownSize2.setDown(75 + i);
                        blackDevice.setUpAndDownSize(upAndDownSize2);
                        lists.add(blackDevice);
                    }
                    BlackDeviceReply blackDeviceReply = new BlackDeviceReply();
                    blackDeviceReply.setDevices(lists);
                    blackDeviceReply.setTagClientId(clientId);
                    peer.sendSNData(blackDeviceReply);
                    break;
                case MsgType.DEVICE_BLACKADD_SET:
                    //添加黑名单
                    NetDevice netDevice = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), NetDevice.class);
                    System.out.println(peerMsg.getBaseMsg().getContent());
                    /*BlackDeviceAddReply blackDeviceAddReply = new BlackDeviceAddReply();
                    peer.sendSNData(blackDeviceAddReply);*/
                    ResultMsg resultMsg8 = new ResultMsg(MsgType.COMMON_SUCCESS);
                    resultMsg8.setReplyType(MsgType.DEVICE_BLACKADD_SET);
                    resultMsg8.setClientId(peer.getPubkey());
                    resultMsg8.setTagClientId(peerMsg.getBaseMsg().getClientId());
                    logger.info(resultMsg8.toString());
                    peer.sendSNData(resultMsg8);
                    break;
                case MsgType.DEVICE_BLACKREMOVE_SET:
                    //移除黑名单
                    NetDevice netDevice2 = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), NetDevice.class);
                    System.out.println(peerMsg.getBaseMsg().getContent());
                    /*BlackDeviceRemoveReply blackDeviceRemoveReply = new BlackDeviceRemoveReply();
                    peer.sendSNData(blackDeviceRemoveReply);*/
                    ResultMsg resultMsg9 = new ResultMsg(MsgType.COMMON_SUCCESS);
                    resultMsg9.setReplyType(MsgType.DEVICE_BLACKREMOVE_SET);
                    resultMsg9.setClientId(peer.getPubkey());
                    resultMsg9.setTagClientId(peerMsg.getBaseMsg().getClientId());
                    logger.info(resultMsg9.toString());
                    peer.sendSNData(resultMsg9);
                    break;
                case MsgType.DEVICE_TWOWIFIGET_REQ:
                    //获取2g网参数信息
                    TwoWifiGetReply twoWifiGetReply = new TwoWifiGetReply();
                    TwoAndFiveWifiInfo twoAndFiveWifiInfog = new TwoAndFiveWifiInfo();
                    twoAndFiveWifiInfog.setEryType("psk");
                    twoAndFiveWifiInfog.setHide(true);
                    twoAndFiveWifiInfog.setUsername("admin");
                    twoAndFiveWifiInfog.setPassword("888888");
                    twoWifiGetReply.setTwoAndFiveWifiInfo(twoAndFiveWifiInfog);
                    twoWifiGetReply.setTagClientId(clientId);
                    peer.sendSNData(twoWifiGetReply);
                    break;
                case MsgType.DEVICE_FIVEWIFIGET_REQ:
                    //获取5g网参数信息
                    FiveWifiGetReply fiveWifiGetReply = new FiveWifiGetReply();
                    TwoAndFiveWifiInfo FiveWifiInfo = new TwoAndFiveWifiInfo();
                    FiveWifiInfo.setEryType("psk");
                    FiveWifiInfo.setHide(true);
                    FiveWifiInfo.setUsername("admin");
                    FiveWifiInfo.setPassword("888888");
                    fiveWifiGetReply.setTwoAndFiveWifiInfo(FiveWifiInfo);
                    fiveWifiGetReply.setTagClientId(clientId);
                    peer.sendSNData(fiveWifiGetReply);
                    break;
                case MsgType.DEVICE_CUSTOMERWIFIGET_REQ:
                    //访客参数信息
                    CustomerWifiGetReply customerWifiGetReply = new CustomerWifiGetReply();
                    TwoAndFiveWifiInfo cusWifiInfo = new TwoAndFiveWifiInfo();
                    cusWifiInfo.setEryType("psk");
                    cusWifiInfo.setHide(true);
                    cusWifiInfo.setUsername("admin");
                    cusWifiInfo.setPassword("888888");
                    customerWifiGetReply.setTwoAndFiveWifiInfo(cusWifiInfo);
                    customerWifiGetReply.setTagClientId(clientId);
                    peer.sendSNData(customerWifiGetReply);
                    break;
                case MsgType.DEVICE_STATICGET_REQ:
                    //静态ip获取
                    StaticIpinfoGetReply staticIpinfoGetReply = new StaticIpinfoGetReply();
                    IpInfo staticIp = new IpInfo();
                    staticIp.setIp("192.168.1.1");
                    staticIp.setChild("192.168.1.1");
                    staticIp.setWlan("192.168.1.1");
                    staticIp.setDns1("192.168.1.1");
                    staticIp.setDns2("192.168.1.1");
                    staticIpinfoGetReply.setIpInfo(staticIp);
                    staticIpinfoGetReply.setTagClientId(clientId);
                    peer.sendSNData(staticIpinfoGetReply);
                    break;
                case MsgType.DEVICE_DYNAMICGET_REQ:
                    //动态ip获取
                    DymaicIpinfoGetReply dymaicIpinfoGetReply = new DymaicIpinfoGetReply();
                    DymacIpInfo dymacIpInfo1 = new DymacIpInfo();
                    dymacIpInfo1.setdType(1);
                    dymacIpInfo1.setDns1("192.168.1.1");
                    dymacIpInfo1.setDns2("192.168.1.1");
                    dymaicIpinfoGetReply.setDymacIpInfo(dymacIpInfo1);
                    dymaicIpinfoGetReply.setTagClientId(clientId);
                    peer.sendSNData(dymaicIpinfoGetReply);
                    break;
                case MsgType.DEVICE_PPPOEGET_REQ:
                    //PPPoE获取
                    PPPoEGetReply ppPoEGetReply = new PPPoEGetReply();
                    PPPoE ppPoE1 = new PPPoE();
                    ppPoE1.setUsername("admin");
                    ppPoE1.setPassword("888888");
                    ppPoEGetReply.setPpPoE(ppPoE1);
                    ppPoEGetReply.setTagClientId(clientId);
                    peer.sendSNData(ppPoEGetReply);
                    break;
                case MsgType.DEVICE_DISKGET_REQ:
                    //磁盘获取
                    DiskGetReply diskGetReply1 = new DiskGetReply();
                    Disk disk1 = new Disk();
                    disk1.setShare(370);
                    disk1.setTotal(500);
                    diskGetReply1.setDisk(disk1);
                    diskGetReply1.setTagClientId(clientId);
                    peer.sendSNData(diskGetReply1);
                    break;
                case MsgType.DEVICE_FILE_UPLOAD_REQ:
                    NetFileInfo netFileInfo = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), NetFileInfo.class);
                    addNetInfoRecord(netFileInfo);
                    break;
                case MsgType.DEVICE_FILE_DOWNLOAD_REQ:
                    NetFileInfo dNetFileInfo = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), NetFileInfo.class);
                    if (StringUtil.hasValue(dNetFileInfo.getFileName())) {
                        addToFileNeedDown(dNetFileInfo, peerMsg.getBaseMsg().getClientId());
                    }
                    break;
                case MsgType.DEVICE_FILE_CONTINUTE_DOWNLOAD_REQ:
                    List<NetFileInfo> needDownNetFileInfos = JsonStringUtil.readValueByList(peerMsg.getBaseMsg().getContent(), NetFileInfo.class);
                    continueDownFile(needDownNetFileInfos, peerMsg.getBaseMsg().getClientId());
                    break;
                case MsgType.DEVICE_FILE_STORAGEITEM_REQ:
                    StorageItem StorageItem = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), StorageItem.class);
                    getStorageItem(StorageItem, peerMsg.getBaseMsg().getClientId());
                    break;
                case MsgType.DEVICE_STORAGEITEM_DELETE_REQ:
                    StorageItem DStorageItem = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), StorageItem.class);
                    deleteItem(DStorageItem, peerMsg.getBaseMsg().getClientId());
                    break;
                case MsgType.DEVICE_STORAGEITEM_RENAME_REQ:
                    FileRenameItem reStorageItem = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), FileRenameItem.class);
                    renameItem(reStorageItem, peerMsg.getBaseMsg().getClientId());
                    break;

                case MsgType.DEVICE_BLACK_STATUS_SET:
                    BlackStatus status = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), BlackStatus.class);
                    setBlackStaus(status, peerMsg.getBaseMsg().getClientId());
                default:
                    break;
            }
        }
    }


    private void setBlackStaus(BlackStatus status, String clientId) {
        ResultMsg resultMsg = new ResultMsg();
        resultMsg.setReplyType(MsgType.DEVICE_BLACK_STATUS_SET);
        ResultInfo resultInfo;
        if (status.isbOpen()) {
            resultInfo = new ResultInfo(true, "打开防火墙成功");
        } else {
            resultInfo = new ResultInfo(true, "关闭防火墙成功");
        }
        resultMsg.setResultInfo(resultInfo);
        resultMsg.setTagClientId(clientId);
        peer.sendSNData(resultMsg);
    }


    private void renameItem(FileRenameItem item, String clientId) {
        if (!FileUtils.isExist(item.getFilePath())) {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.setReplyType(MsgType.DEVICE_STORAGEITEM_RENAME_REQ);
            ResultInfo resultInfo = new ResultInfo(false, "文件不存在");
            resultMsg.setResultInfo(resultInfo);
            resultMsg.setTagClientId(clientId);
            peer.sendSNData(resultMsg);
        } else {
            String npath = "";
            String oldpath = "";
            if (item.getFileType() == 0) {
                oldpath = Constants.FILE_DIR + "\\movie\\" + item.getOldName();
                npath = Constants.FILE_DIR + "\\movie\\" + item.getNewName();
            } else if (item.getFileType() == 1) {
                oldpath = Constants.FILE_DIR + "\\photo\\" + item.getOldName();
                npath = Constants.FILE_DIR + "\\photo\\" + item.getNewName();
            } else if (item.getFileType() == 2) {
                oldpath = Constants.FILE_DIR + "\\music\\" + item.getOldName();
                npath = Constants.FILE_DIR + "\\music\\" + item.getNewName();
            }
            if (StringUtil.hasValue(npath)) {
                boolean bRename = FileUtils.renameFile(npath, oldpath);
                ResultMsg resultMsg = new ResultMsg();
                resultMsg.setReplyType(MsgType.DEVICE_STORAGEITEM_DELETE_REQ);
                ResultInfo resultInfo;
                if (bRename) {
                    resultInfo = new ResultInfo(true, "文件重命名成功");
                } else {
                    resultInfo = new ResultInfo(true, "文件重命名失败");
                }
                resultMsg.setResultInfo(resultInfo);
                resultMsg.setTagClientId(clientId);
                peer.sendSNData(resultMsg);
            } else {
                ResultMsg resultMsg = new ResultMsg();
                resultMsg.setReplyType(MsgType.DEVICE_STORAGEITEM_RENAME_REQ);
                ResultInfo resultInfo = new ResultInfo(false, "文件类别异常");
                resultMsg.setResultInfo(resultInfo);
                resultMsg.setTagClientId(clientId);
                peer.sendSNData(resultMsg);
            }
        }
    }

    private void deleteItem(StorageItem storageItem, String clientId) {
        if (!FileUtils.isExist(storageItem.getFilePath())) {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.setReplyType(MsgType.DEVICE_STORAGEITEM_DELETE_REQ);
            ResultInfo resultInfo = new ResultInfo(false, "文件不存在");
            resultMsg.setResultInfo(resultInfo);
            resultMsg.setTagClientId(clientId);
            peer.sendSNData(resultMsg);
        } else {
            boolean bdelete = FileUtils.deleteFile(storageItem.getFilePath());
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.setReplyType(MsgType.DEVICE_STORAGEITEM_DELETE_REQ);
            ResultInfo resultInfo;
            if (bdelete) {
                resultInfo = new ResultInfo(true, "文件已删除");
            } else {
                resultInfo = new ResultInfo(true, "文件删除错误");
            }
            resultMsg.setResultInfo(resultInfo);
            resultMsg.setTagClientId(clientId);
            peer.sendSNData(resultMsg);
        }
    }

    /**
     * 通过文件类别获取文件
     *
     * @param storageItem
     * @param clientId
     */
    private void getStorageItem(StorageItem storageItem, String clientId) {
        String filePath = "";
        if (storageItem.getFileType() == 0) {
            filePath = Constants.FILE_DIR + "\\movie";
        } else if (storageItem.getFileType() == 1) {
            filePath = Constants.FILE_DIR + "\\photo";
        } else if (storageItem.getFileType() == 2) {
            filePath = Constants.FILE_DIR + "\\music";
        }
        if (StringUtil.hasValue(filePath)) {
            FileStorageItemReplyMsg fileStorageItemReplyMsg = new FileStorageItemReplyMsg();
            if (storageItem.getFileType() == 1) {
                List<DateStorageItem> dateStorageItems = FileUtils.getDateStorageItem(filePath);
                fileStorageItemReplyMsg.setDateItems(dateStorageItems);
            } else {
                List<StorageItem> lst = FileUtils.getStorageItemsByDir(filePath);
                fileStorageItemReplyMsg.setItems(lst);
            }
            fileStorageItemReplyMsg.setTagClientId(clientId);
            peer.sendSNData(fileStorageItemReplyMsg);
        } else {

        }
    }


    /**
     * 需要重新下载的字节
     *
     * @param netFileinfos
     * @param clientId
     */
    private void continueDownFile(List<NetFileInfo> netFileinfos, String clientId) {
        //String filePath = "";
        String filePath = Constants.FILE_DIR + netFileinfos.get(0).getFileName();
        NetFileInfoRecord netFileInfoRecord = new NetFileInfoRecord();
        netFileInfoRecord.filePath = filePath;
        for (NetFileInfo item : netFileinfos) {
            item.setFilePath(filePath);
        }
        netFileInfoRecord.addAndTidy(netFileinfos);
        netFileInfoRecord.setClientId(clientId);
        boolean result = checkAndSendFile(clientId, netFileInfoRecord);
        if (result) {
            if (this.needContinueDownFileDir.containsKey(filePath) == false) {
                this.needContinueDownFileDir.put(filePath, netFileInfoRecord);
            }
        }
    }

    /**
     * 读取继续需要下载的文件
     */
    private synchronized void readContinueDownFile() {
        try {
            Thread.sleep(20);
            Map<String, NetFileInfoRecord> needRemoves = new HashMap<>();
            for (String item : needContinueDownFileDir.keySet()) {
                NetFileInfoRecord netFileInfoRecord = needContinueDownFileDir.get(item);
                if (netFileInfoRecord.getFileContinueRecord().isHasRead() && netFileInfoRecord.getNetFileInfos().size() == 0) {
                    needRemoves.put(item, netFileInfoRecord);
                    continue;
                } else {
                    netFileInfoRecord.readContinueFile();
                    List<NetFileInfo> tags = netFileInfoRecord.dequeue(100);
                    sendNetFileInfo(netFileInfoRecord.getClientId(), tags);
                }
            }
            for (String item : needRemoves.keySet()) {
                if (needContinueDownFileDir.containsKey(item)) {
                    needContinueDownFileDir.remove(item);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void sendNetFileInfo(String clientId, List<NetFileInfo> tags) {
        for (NetFileInfo nitem : tags) {
            System.out.println("currentIndex:" + nitem.getCurrentIndex() + "size:" + nitem.getSize());
            nitem.transferToHBytes();
            FileUploadMsg fileUploadMsg = new FileUploadMsg();
            fileUploadMsg.setNetFileInfo(nitem);
            fileUploadMsg.setTagClientId(clientId);
            this.getPeer().sendSNData(fileUploadMsg);
        }
    }


    private boolean checkAndSendFile(String clientId, NetFileInfoRecord netFileInfoRecord) {
        boolean isExist = FileUtils.isExist(netFileInfoRecord.filePath);
        if (!isExist) {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.setReplyType(MsgType.DEVICE_FILE_DOWNLOAD_REQ);
            ResultInfo resultInfo = new ResultInfo(false, "文件不存在");
            resultMsg.setResultInfo(resultInfo);
            resultMsg.setTagClientId(clientId);
            peer.sendSNData(resultMsg);
        }
        return isExist;
    }


    public void addToFileNeedDown(NetFileInfo netFileInfo, String clientId) {
        String filePath = Constants.FILE_DIR + netFileInfo.getFileName();
        NetFileInfoRecord netFileInfoRecord = new NetFileInfoRecord();
        netFileInfoRecord.setClientId(clientId);
        netFileInfoRecord.filePath = filePath;
        boolean result = checkAndSendFile(clientId, netFileInfoRecord);
        if (result) {
            if (this.readFileDir.containsKey(filePath) == false) {
                this.readFileDir.put(filePath, netFileInfoRecord);
            }
        }
    }

    private void addNetInfoRecord(NetFileInfo netFileInfo) {
        netFileInfo.transferToBytes();
        if (netFileDir.containsKey(netFileInfo.getFileName())) {
            netFileDir.get(netFileInfo.getFileName()).add(netFileInfo);
        } else {
            NetFileInfoRecord netFileInfoRecord = new NetFileInfoRecord();
            netFileInfoRecord.add(netFileInfo);
            netFileDir.put(netFileInfo.getFileName(), netFileInfoRecord);
        }
    }

    public synchronized void sendFile() throws InterruptedException {
        Thread.sleep(30);
        Map<String, String> needRemove = new HashMap<>();
        for (String item : readFileDir.keySet()) {
            NetFileInfoRecord netFileInfoRecord = readFileDir.get(item);
            List<NetFileInfo> netFileInfos = netFileInfoRecord.dequeue(100);
            if (netFileInfos.size() == 0 && netFileInfoRecord.bEnd) {
                needRemove.put(netFileInfoRecord.filePath, netFileInfoRecord.filePath);
            } else {
                sendNetFileInfo(netFileInfoRecord.getClientId(), netFileInfos);
            }
        }
        for (String item : needRemove.keySet()) {
            if (readFileDir.containsKey(item)) {
                readFileDir.remove(item);
            }
        }
    }

    private synchronized void readFile() throws InterruptedException {
        Thread.sleep(20);
        for (String item : readFileDir.keySet()) {
            NetFileInfoRecord netFileInfoRecord = readFileDir.get(item);
            if (netFileInfoRecord.bEnd) {
                continue;
            } else {
                netFileInfoRecord.readFile();
            }
        }
    }

    private synchronized void writeFile() {
        try {
            for (String key : netFileDir.keySet()) {
                NetFileInfoRecord netFileInfoRecord = netFileDir.get(key);
                if (netFileInfoRecord.getNetFileInfos().size() > 100) {
                    netFileInfoRecord.writeToFile(100);
                    peer.keepConnect();
                } else if (netFileInfoRecord.hasTimeout(200)) {
                    if (netFileInfoRecord.hasContent()) {
                        peer.keepConnect();
                        netFileInfoRecord.writeToFile(100);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ClientSocket getPeer() {
        return peer;
    }

    public void setPeer(ClientSocket peer) {
        this.peer = peer;
    }
}
